package com.example.work;

import android.annotation.SuppressLint;
import android.content.Context;
// 导入必要的Android SDK类和接口
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;

import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.ArrayList;
import java.util.List;

public class Diary extends AppCompatActivity {

    // 数据库服务类对象
    DBService myDb;
    // 界面组件
    private Button mBtnAdd, person;
    private ListView lv_note;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary); // 设置布局
        // 初始化数据库服务类
        myDb = new DBService(this);
        // 初始化界面组件和事件
        init();
    }

    @SuppressLint("Range")
    public void init(){
        // 初始化界面组件
        mBtnAdd = findViewById(R.id.btn_add);
        person = findViewById(R.id.btn_person);
        lv_note = findViewById(R.id.lv_note);

        // 创建用于存储数据库查询结果的列表
        List<Values> valuesList = new ArrayList<>();
        // 获取数据库可读对象
        SQLiteDatabase db = myDb.getReadableDatabase();
        // 执行查询操作
        Cursor cursor = db.query(DBService.TABLE, null, null, null, null, null, null);
        // 遍历Cursor并填充Values对象列表
        if(cursor.moveToFirst()){
            Values values;
            while (!cursor.isAfterLast()){
                values = new Values();
                values.setId(Integer.valueOf(cursor.getString(cursor.getColumnIndex(DBService.ID))));
                values.setTitle(cursor.getString(cursor.getColumnIndex(DBService.TITLE)));
                values.setContent(cursor.getString(cursor.getColumnIndex(DBService.CONTENT)));
                values.setTime(cursor.getString(cursor.getColumnIndex(DBService.TIME)));
                valuesList.add(values);
                cursor.moveToNext();
            }
        }
        cursor.close();
        db.close();

        // 设置ListView的适配器
        final MyBaseAdapter myBaseAdapter = new MyBaseAdapter(valuesList, this, R.layout.activity_noteitem);
        lv_note.setAdapter(myBaseAdapter);

        // 设置添加按钮的点击事件
        mBtnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Diary.this, com.example.work.NoteEdit.class);
                startActivity(intent);
            }
        });
        // 设置个人中心按钮的点击事件
        person.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Diary.this, Personalcenter.class);
                startActivity(intent);
            }
        });
        // 设置ListView的条目点击事件
        lv_note.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(Diary.this, Show.class);
                Values values = (Values) lv_note.getItemAtPosition(position);
                // 通过Intent传递数据
                intent.putExtra(DBService.TITLE, values.getTitle().trim());
                intent.putExtra(DBService.CONTENT, values.getContent().trim());
                intent.putExtra(DBService.TIME, values.getTime().trim());
                intent.putExtra(DBService.ID, values.getId().toString().trim());
                startActivity(intent);
            }
        });

        // 设置ListView的长按删除事件
        lv_note.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                final Values values = (Values) lv_note.getItemAtPosition(position);
                new AlertDialog.Builder(Diary.this)
                        .setTitle("提示框")
                        .setMessage("是否删除?")
                        .setPositiveButton("yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 执行删除操作
                                SQLiteDatabase db = myDb.getWritableDatabase();
                                db.delete(DBService.TABLE, DBService.ID + "=?", new String[]{String.valueOf(values.getId())});
                                db.close();
                                // 刷新适配器和ListView
                                myBaseAdapter.removeItem(position);
                                lv_note.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        myBaseAdapter.notifyDataSetChanged();
                                    }
                                });
                            }
                        })
                        .setNegativeButton("no", null).show();
                return true;
            }
        });
    }

    // 自定义的ListView适配器
    class MyBaseAdapter extends BaseAdapter {
        // 用于存储数据列表、上下文和布局ID
        private List<Values> valuesList;
        private Context context;
        private int layoutId;

        public MyBaseAdapter(List<Values> valuesList, Context context, int layoutId) {
            this.valuesList = valuesList;
            this.context = context;
            this.layoutId = layoutId;
        }

        // 实现BaseAdapter的抽象方法
        @Override
        public int getCount() {
            return valuesList.size();
        }

        @Override
        public Object getItem(int position) {
            return valuesList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(layoutId, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.title = convertView.findViewById(R.id.tv_title);
                viewHolder.content = convertView.findViewById(R.id.tv_content);
                viewHolder.time = convertView.findViewById(R.id.tv_time);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            // 绑定数据到视图
            viewHolder.title.setText(valuesList.get(position).getTitle());
            viewHolder.content.setText(valuesList.get(position).getContent());
            viewHolder.time.setText(valuesList.get(position).getTime());
            return convertView;
        }

        // 移除列表项的方法
        public void removeItem(int position) {
            valuesList.remove(position);
        }
    }

    // 内部静态类，用于ViewHolder模式
    static class ViewHolder {
        TextView title;
        TextView content;
        TextView time;
    }
}